<?php
declare (strict_types = 1);

namespace app\admin\middleware;

use app\Request;
use app\utils\Jwt;
use think\App;

class CheckLogin
{
    /**
     * @var App
     */
    private $app;

    public static function __make(App $app) {
        $instance = new static();
        $instance->app = $app;
        return $instance;
    }
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        return $this->app->invokeMethod([$this, 'check'], [$request, $next], true);
    }

    public function check(Request $request, \Closure $next, Jwt $jwt) {
        $token = $request->header('Authorization');
        if (empty($token)) {
            return json(error('请先登录'));
        }
        $parse_ret = $jwt->parseToken($token);
        if ($parse_ret['code'] != 200) {
            return json($parse_ret);
        }
        $request->admin = $parse_ret['data'];
        return $next($request);
    }
}
